package com.app.controller;

import com.app.feign.PileOpenFeign;
import com.app.service.OrdersServer;
import com.app.service.UserService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.entity.Code;
import com.common.entity.Orders;
import com.common.entity.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author 王鑫
 * @create 2020 -11 -24 12:00
 */
@Api(tags = "订单模块")
@RestController
@RequestMapping("/orders")

//@CrossOrigin
public class OrdersController {

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    OrdersServer ordersServer;
    @Autowired
    UserService userService;
    //引入openFeign
    @Autowired
    PileOpenFeign pileOpenFeign;

    /**
     * 添加订单
     *
     * @param orders
     * @param userId
     * @param pileId
     * @return
     */
    @ApiOperation(value = "添加订单")
    @PostMapping("/add/{userId}/{pileId}")
    public ResponseResult addOrders(
            @ApiParam(name = "orders", value = "订单对象", required = true) Orders orders,
            @ApiParam(name = "userId", value = "用户id", required = true) @PathVariable("userId") String userId,
            @ApiParam(name = "pileId", value = "电桩id", required = true) @PathVariable("pileId") String pileId) {
        try {
            //System.out.println("feign:" + pileOpenFeign.getOne(pileId));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss a E");
            System.out.println("发送订单信息时间:" + simpleDateFormat.format(new Date()));
            //发消息给队列处理把订单加入数据库和redis
            Orders order = ordersServer.createOrders(orders, userId, pileId);
            rabbitTemplate.convertAndSend("exchangetopicsdelay", "delay", order,
                    new MessagePostProcessor() {
                        @Override
                        public Message postProcessMessage(Message message) throws AmqpException {
                            //设置延迟发送
                            message.getMessageProperties().setDelay(10000);
                            return message;
                        }
                    });
            return ResponseResult.success(Code.REQUEST_SUCCESS).Data(null).Message("发送成功");
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResponseResult.error(Code.REQUEST_ERROR);
        }
    }

    /**
     * 添加订单(手机号)
     *
     * @return
     */
    @ApiOperation(value = "最终添加订单(账号)")
    @PostMapping("/addorders/{userPhone}/{pileId}")
    public ResponseResult addOrdersByPhone(
            @ApiParam(name = "orders", value = "订单对象", required = true) Orders orders,
            @ApiParam(name = "userPhone", value = "用户电话(账号)", required = true) @PathVariable("userPhone") String userPhone,
            @ApiParam(name = "pileId", value = "电桩id", required = true) @PathVariable("pileId") String pileId) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss a E");
            //得出完整的orders订单
            Orders order = ordersServer.generateOrders(orders, userPhone, pileId);
            //发消息给队列处理把订单加入数据库和redis
            System.out.println("------------开始发送订单----------------"+simpleDateFormat.format(new Date()));
            rabbitTemplate.convertAndSend("exchangetopicsdelay", "delay", order,
                    new MessagePostProcessor() {
                        @Override
                        public Message postProcessMessage(Message message) throws AmqpException {
                            //设置延迟发送
                            message.getMessageProperties().setDelay(10000);
                            return message;
                        }
                    });
            return ResponseResult.success(Code.REQUEST_SUCCESS).Data(null).Message("发送成功");
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResponseResult.error(Code.REQUEST_ERROR);
        }

    }

    /**
     * 通过id删除订单
     *
     * @param ordersId
     * @return
     */
    @ApiOperation(value = "通过id删除订单")
    @DeleteMapping("/delete/{ordersId}")
    public ResponseResult deleteOrders(
            @ApiParam(name = "ordersId", value = "订单id", required = true) @PathVariable("ordersId") String ordersId) {
        try {
            ordersServer.deleteOrderById(ordersId);
            return ResponseResult.success(Code.REQUEST_SUCCESS);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResponseResult.error(Code.REQUEST_ERROR);
        }
    }

    /**
     * 修改订单
     *
     * @return
     */
    @ApiOperation(value = "修改订单")
    @GetMapping("/updata")
    public ResponseResult updataOrders(
            @ApiParam(name = "orders", value = "订单对象", required = true) Orders orders) {
        try {

            ordersServer.updataOrder(orders);
            return ResponseResult.success(Code.REQUEST_SUCCESS);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResponseResult.error(Code.REQUEST_ERROR);
        }
    }

    /**
     * 通过id查询订单
     */
    @ApiOperation(value = "通过id查询订单")
    @GetMapping("/selectById/{ordersId}")
    public ResponseResult updataOrders(
            @ApiParam(name = "ordersId", value = "订单id", required = true)
            @PathVariable("ordersId") String ordersId) {
        try {
            Orders order = ordersServer.selectOrderById(ordersId);
            return ResponseResult.success(Code.REQUEST_SUCCESS).Data("idorder", order);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResponseResult.error(Code.REQUEST_ERROR);
        }
    }

    /**
     * 查询所有订单
     */
    @ApiOperation(value = "查询所有订单")
    @GetMapping("/selectAllOrders")
    public ResponseResult selectAllOrders() {
        try {
            List<Orders> orders = ordersServer.selectAllOrders();
            return ResponseResult.success(Code.REQUEST_SUCCESS).Data("allorders", orders);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResponseResult.error(Code.REQUEST_ERROR);
        }
    }

    /**
     * 分页查询所有订单
     */
    @ApiOperation(value = "分页查询所有订单")
    @GetMapping("/selectOrdersByPage/{pageIndex}/{pageSize}")
    public ResponseResult selectOrdersByPage(
            @ApiParam(name = "pageIndex", value = "当前页码", required = true) @PathVariable("pageIndex") int pageIndex,
            @ApiParam(name = "pageSize", value = "页大小", required = true) @PathVariable("pageSize") int pageSize) {
        try {
            //构造分页对象
            Page<Orders> page = new Page<>(pageIndex, pageSize);
            //开启分页
            ordersServer.selectOrdersByPage(page);
            //获取数据总条数
            long pageTotal = page.getTotal();
            //获取当前页信息
            List<Orders> records = page.getRecords();
            return ResponseResult.success(Code.REQUEST_SUCCESS).Data("allorderslimit", records);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResponseResult.error(Code.REQUEST_ERROR);
        }
    }

    /**
     * 多条件分页查询订单
     */
    @ApiOperation(value = "多条件分页查询订单")
    @GetMapping("/selectOrdersByPageAndCondition/{pageIndex}/{pageSize}")
    public ResponseResult selectOrdersByPageAndCondition(
            @ApiParam(name = "orders", value = "订单对象", required = true) Orders orders,
            @ApiParam(name = "pageIndex", value = "当前页码", required = true) @PathVariable("pageIndex") int pageIndex,
            @ApiParam(name = "pageSize", value = "页大小", required = true) @PathVariable("pageSize") int pageSize) {
        try {
            //构造分页对象
            Page<Orders> page = new Page<>(pageIndex, pageSize);
            //开启分页
            ordersServer.selectOrdersByPageAndCondition(page, orders);
            //开启分页
            ordersServer.selectOrdersByPageAndCondition(page, orders);
            //获取数据总条数
            long pageTotal = page.getTotal();
            //获取当前页信息
            List<Orders> records = page.getRecords();
            return ResponseResult.success(Code.REQUEST_SUCCESS).Data("allorderslimitCondition", records);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResponseResult.error(Code.REQUEST_ERROR);
        }
    }

    /**
     * 通过UserId查询订单
     */
    @ApiOperation(value = "通过UserId查询订单")
    @GetMapping("/selectByuserId/{userId}")
    public ResponseResult selectOrderByUserId(@ApiParam(name = "userId", value = "用户id", required = true)
                                              @PathVariable("userId") String userId) {
        try {
            List<Orders> ordersList = ordersServer.selectOrderByUserId(userId);
            return ResponseResult.success(Code.REQUEST_SUCCESS).Data("allorders", ordersList);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResponseResult.error(Code.REQUEST_ERROR);
        }
    }

    /**
     * 通过用户电话(账号)查询订单
     */
    @ApiOperation(value = "通过用户电话(账号)查询订单")
    @GetMapping("/selectByuserPhone")
    public ResponseResult selectOrderByUserPhone(
            @ApiParam(name = "phone", value = "用户电话", required = true)
            @RequestParam("phone") String phone) {
        try {
            return userService.getOrderByPhone(phone);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResponseResult.error(Code.REQUEST_ERROR);
        }
    }

}
